package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Flight;
import model.FlightIO;

/**
 * Servlet implementation class CheckSeats
 */
public class CheckSeats extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckSeats() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	/**
	 * The doPost method gets all of the paremeters for the seats from the ajax call.
	 * Then there is a check to see if there are enough seats. If there is return that
	 * the seats were added and if not return the failure message.
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get parameters
		String classType = request.getParameter("classType");
		int firstClass = Integer.parseInt(request.getParameter("firstClass"));
		int business = Integer.parseInt(request.getParameter("business"));
		int economy = Integer.parseInt(request.getParameter("economy"));
		int seats = Integer.parseInt(request.getParameter("seats"));
		int planeID = Integer.parseInt(request.getParameter("planeID"));
		int flightID = Integer.parseInt(request.getParameter("flightID"));

		//Get session and cart
		HttpSession session = request.getSession();
		ArrayList<Flight> cart = (ArrayList<Flight>) session.getAttribute("shoppingCart");
		
		//Set the seats for the correct flight
		if(cart != null){
			for(Flight flight : cart){
				if(flight.getId() == flightID){
					flight.setSeats(seats);
				}
			}
		} 
		
		FlightIO flightIO = new FlightIO();
		
		//Get flight
		int reservedSeats = 0;
		if(classType.equals("Economy")){
			reservedSeats = economy;
			classType = "economy";
		} else if(classType.equals("Business")){
			reservedSeats = business;
			classType = "business";
		} else {
			reservedSeats = firstClass;
			classType = "first_class";
		}
		
		//Verify number of requested seats
		boolean added = flightIO.checkSeats(seats, planeID, reservedSeats, classType);
		
		//Give success/failure message
		if(added){
			response.getWriter().write("added");
		} else {
			response.getWriter().write("notAdded");
		}
		
	}

}
